package org.idea.spring.framework.mybatis.factorybean;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSession;
import org.idea.spring.framework.mybatis.config.MybatisConfigRegistrar;
import org.idea.spring.framework.mybatis.mapper.UserMapper;
import org.idea.spring.framework.mybatis.utils.AnnotationUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Configuration;

import java.util.Set;


/**
 * @Author linhao
 * @Date created in 10:09 上午 2021/6/5
 */
@Configuration
@AutoConfigureAfter(MybatisConfigRegistrar.class)
public class MapperFactoryBeanRegister implements BeanFactoryPostProcessor {


    /**
     * 弊端，对于每个Bean的注册都比较繁琐
     *
     * @param beanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SqlSession sqlSession = MybatisConfigRegistrar.getSqlSession();
        for (Class mapperClass : MybatisConfigRegistrar.getMapperClassSet()) {
            String className = mapperClass.getSimpleName();
            char[] chars = className.substring(0, 1).toCharArray();
            char chars1 = (char) (chars[0] + 32);
            String newClassName = chars1 + className.substring(1);
            beanFactory.registerSingleton(newClassName, sqlSession.getMapper(mapperClass));
        }
        System.out.println("======== register userMapper ========");
    }
}
